<?php

/**
 * 中奖统计 每2分运行一次
 *
 * @author fx
 */
require_once dirname(__DIR__) . "/cronBase.php";

use Common\Bridge;
use Notice\Sys;

class offer extends cronBase
{

    public function doDefault()
    {
        global $argv;
        //计算时间
        $now = date('Y-m-d H:i:00');
        offer_log('Offer_Run:[' . $now);
        $pdo = Bridge::pdo(Bridge::DB_CENTER_W);
        $select_sql = "SELECT * FROM `Active` WHERE EndTime < '" . $now . "' and `Status` = 1";
        $obj = $pdo->query($select_sql);
        $rs = $obj->fetchAll();
        if (count($rs) > 0) {
            foreach ($rs as $v) {

                $rs = self::selectUser($v['Id']);
                if ($rs === false) {
                    offer_log('Offer_Fail:[' . $v['Id']);
                } else {
                    //todo 推送消息
                    offer_log('Offer_OK:[' . $v['Id']);
                    self::send($v);
                }
                \Center\Active::update($v['Id'], ['Status' => 2]);
            }
        }
        $pdo->close();
        Bridge::pdo(Bridge::DB_CENTER_W, 'force_close');
        $pdo = null;
    }

    public static function selectUser($id)
    {
        //查找最大值
        $pdo = Bridge::pdo(Bridge::DB_CENTER_W);
        $select_sql = "SELECT count(Id) as Num FROM `ActiveOffer` WHERE ActiveId=$id and  `Status` = 1";
        $obj = $pdo->query($select_sql);
        $num = $obj->fetch();
        if ($num['Num'] > 0) {
            return false;
        } else {
            $sql2 = "SELECT MAX(`OfferPrice`) as pri FROM `ActiveOffer` WHERE ActiveId=$id and `Status` = 0";
            $obj2 = $pdo->query($sql2);
            $price = $obj2->fetch();
            $price = $price['pri'];
            if (empty($price)) {
                return false;
            }
            $sql3 = "SELECT count(Id) as num2 FROM `ActiveOffer` WHERE ActiveId=$id and `Status` = 0 and OfferPrice = '" . $price . "'";
            $obj3 = $pdo->query($sql3);
            $num3 = $obj3->fetch();
            if ($num3['num2'] == 1) {
                $sql4 = "SELECT Id FROM `ActiveOffer` WHERE ActiveId=$id and `Status` = 0 and OfferPrice = '" . $price . "'";
                $obj4 = $pdo->query($sql4);
                $aoid = $obj4->fetch();
                $rs = \Center\ActiveOffer::update($aoid['Id'], ['Status' => 1]);
                if ($rs !== false) {
                    return true;
                }
            } else {
                $sql4 = "update `ActiveOffer` set `Status`=2 where ActiveId=$id and OfferPrice = '" . $price . "'";
                $pdo->exec($sql4);
                $rs = self::selectUser($id);

                return $rs;
            }
        }

        return true;
    }

    public static function send($ainfo)
    {
        $pdo = Bridge::pdo(Bridge::DB_CENTER_W);
        $id = $ainfo['Id'];
        $shopinfo = \Center\Shop::getInfoByIds($ainfo['ShopId']);
        $select_sql = "SELECT Status, UserId, OfferPrice FROM `ActiveOffer` WHERE ActiveId=$id";
        $obj = $pdo->query($select_sql);
        $res = $obj->fetchAll();
        $uid = [];
        if (is_array($res) && count($res) > 0) {
            foreach ($res as $v) {
                if ($v['Status'] == 1) {
                    //中奖
                    if ($ainfo['RewardType'] == 2) {
                        $uc = [
                            'UserId' => $v['UserId'],
                            'CouponId' => $ainfo['CouponId'],
                            'ShopId' => $ainfo['ShopId'],
                            'Amount' => $ainfo['Amount'],
                            'Status' => 1,
                            'StartTime' => date('Y-m-d H:i:s'),
                            'EndTime' => date('Y-m-d H:i:s', strtotime('+7 day')),
                        ];
                        Center\UserCoupon::add($uc);
                    } else {
                        \Center\QrCode::addQrCode($id, $v['UserId'], \Center\QrCode::TYPE_ACT);
                    }

                    $msg = '恭喜您获得［' . $shopinfo['Name'] . '］活动商家赠送的礼品';
                    $data = [
                        'tid' => Sys::TID_MSG_SHOP, // 消息分类ID
                        'type' => Sys::TYPE_MSG_ACT_REWARD, // 消息类型ID
                        'userid' => 0, //用户ID
                        'activeid' => $id, //活动ID
                        'shopid' => $ainfo['ShopId'], //商铺ID
                        'cont' => $msg, // 消息内容
                        'itemid' => 0, //邀请的用户id等
                        'url' => 'gold://app/prizeResult?id=' . $id,
                        't' => time()// 时间戳
                    ];
                    \Notice\Sys::addNotice($v['UserId'], Sys::TID_MSG_SHOP, $data);

                    $sql5 = "update `ActiveOffer` set `Status`=0 where ActiveId=$id and `Status` = 2";
                    $pdo->exec($sql5);

                } else {
                    $uid[] = $v['UserId'];
                    if (count($uid) >= 500) {
                        self::sendfail($uid, $id, $shopinfo, $ainfo['Name']);
                        $uid = [];
                    }
                }
                if (count($uid) > 0) {
                    self::sendfail($uid, $id, $shopinfo, $ainfo['Name']);
                    $uid = [];
                }
            }
        } else {
            return false;
        }

        return true;
    }

    public static function sendfail($uid, $id, $shopinfo, $aname)
    {
        $msg = '［' . $aname . '］活动结果公示';
        $data = [
            'tid' => Sys::TID_MSG_SHOP, // 消息分类ID
            'type' => Sys::TYPE_MSG_ACT_RESULT, // 消息类型ID
            'userid' => 0, //用户ID
            'activeid' => $id, //活动ID
            'shopid' => $shopinfo['ShopId'], //商铺ID
            'cont' => $msg, // 消息内容
            'itemid' => 0, //邀请的用户id等
            //'url' => 'gold://app/activeResult?id='.$id,
            'url' => 'gold://app/url?url=' . urlencode("http://m.jinguonet.com/app/gs.php?id={$id}&uid={$uid}"),
            't' => time()// 时间戳
        ];
        \Notice\Sys::addNotice($uid, Sys::TID_MSG_SHOP, $data);
    }
}

$app->run();